<template>
  <div class="logo">
    <img :src="state.logoSrc" class="logoImg" />
  </div>
  <a-menu
    v-model:selectedKeys="state.selectedKeys"
    v-model:openKeys="state.openKeys"
    mode="inline"
    theme="dark"
    @openChange="openChange"
  >
    <!-- 循环一级 -->
    <template v-bind:key="item.id" v-for="item in state.treeData">
      <a-sub-menu v-if="item.type === 'category'" v-bind:key="item.id">
        <template #title>{{ item.name }}</template>

        <!-- 循环二级 -->
        <template v-bind:key="item2.key" v-for="item2 in item.children">
          <a-menu-item
            v-if="item2.type !== 'category'"
            v-bind:key="item2.id"
            @click="menuClick(item2)"
          >
            {{ item2.name }}
          </a-menu-item>
        </template>
      </a-sub-menu>
      <a-menu-item v-else v-bind:key="item.id" @click="menuClick(item)">
        {{ item.name }}
      </a-menu-item>
    </template>
  </a-menu>
</template>



<script lang="ts">
import { defineComponent } from "vue";
import { reactive } from "@vue/reactivity";
import { useRouter } from "vue-router";
import { getSession, setSession } from "@/util/utils";

export default defineComponent({
  name: "leftMenu",
  components: {},
  setup() {
    const router = useRouter();
    const openKeys = getSession("devcloud-openKeys");
    const selectedKeys = getSession("devcloud-selectedKeys");

    const state = reactive({
      selectedKeys: selectedKeys ? selectedKeys : [],
      openKeys: openKeys ? openKeys : [],
      logoSrc: require("../../../static/logo.png"),
      treeData: [],
    });

    const listMenu = async () => {
      let owner: any = getSession("devcloud-auth");
      state.treeData = owner.accountMenu;
    }

    const menuClick = (item: any) => {
      if (item.type === "menu") {
        setSession("devcloud-selectedKeys", [item.id]);
        setSession("devcloud-openKeys", state.openKeys);
        router.push({ path: item.path });
      } else if (item.type === "link") {
        window.open(item.path, "_blank");
      }
    }

    const openChange = (openKeys: string[]) => {
      const latestOpenKey = openKeys.filter((item) => {
        if (state.openKeys instanceof Array) {
          if (!state.openKeys.includes(item + "")) {
            return true;
          }
        }
        return false;
      });
      state.openKeys = latestOpenKey;
    }

    listMenu();

    return {
      state,
      menuClick,
      openChange,
    }
  },
});
</script>

<style lang="less" scoped>
.logo {
  margin: 16px;

  .logoImg{
    width: 100px;
  }
}
</style>